#!/usr/bin/python

import sys
import os
import locale
import subprocess

def iconv(txt, fcode, tcode):
    return txt.decode(fcode).encode(tcode)

def cdict(word):
    return subprocess.Popen(['cdict.bin', word], 
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT).stdout.read()

def main():
    if len(sys.argv) == 1:
        subprocess.call(['cdict.bin'])
        sys.exit(0)

    encoding = locale.getpreferredencoding()
    p = subprocess.Popen(['less', '-r'], stdin=subprocess.PIPE)
    ofile = p.stdin

    for word in sys.argv[1:]:
        word = iconv(word, encoding, 'gb2312')
        result = cdict(word)
        result = iconv(result, 'gb2312', encoding)
        ofile.write(result)
    ofile.close()

    sts = os.waitpid(p.pid, 0)

if __name__ == '__main__':
    main()
